﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

namespace EasyDDD.Host.WebAPI
{
    /// <summary>
    /// 根据HttpContext终结点判断权限
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class AuthorizeEndpointAttribute : Attribute, IAuthorizationFilter
    {
        public AuthorizeEndpointAttribute()
        {
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User.Identity?.Name == "superadmin")
            {
                return;
            }
            if (context.HttpContext.User.IsInRole("superadmin"))
            {
                return;
            }
            if (context.HttpContext.User.HasClaim(ClaimTypes.Role, "superadmin"))
            {
                return;
            }

            //var action = context.HttpContext.GetRouteValue("action");
            //var endpoint = context.HttpContext.Features.Get<IEndpointFeature>()?.Endpoint;          
            //var endpoint = context.HttpContext.Features.FirstOrDefault(e=>e.Key.Name == "Endpoint").Value;

            var endpoint = context.HttpContext.GetEndpoint();


            if (string.IsNullOrEmpty(endpoint?.DisplayName))
            {
                throw new Exception("Endpoint获取错误！");
            }

            if (!context.HttpContext.User.HasClaim(ClaimTypes.Role, endpoint.DisplayName))
            {
                throw new Exception("您没有该权限！");
            }
        }
    }
}